package org.nmgyjt.springboot.utils;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.*;

public class JsonDataSecurity {
//
//    private static final String SECRET_KEY = "YourSecretKey123";
    private static final ObjectMapper objectMapper = new ObjectMapper();

    // 对JSON对象按照键名排序并加密
    public static String encryptJsonData(Object jsonData,String secretKey) throws Exception {
        String jsonString = objectMapper.writeValueAsString(jsonData);
        Map<String, Object> sortedMap = sortJsonObject(jsonString);
        String sortedJsonString = objectMapper.writeValueAsString(sortedMap);
        return encryptString(secretKey,sortedJsonString);
    }

    // 解密并反序列化为JSON对象
    public static Map<String, Object> decryptAndParseJsonData(String encryptedData,String secretKey) throws Exception {
        String decryptedString = decryptString(secretKey,encryptedData);
        return objectMapper.readValue(decryptedString, HashMap.class);
    }

    // 按照键名字母顺序对JSON对象进行排序
    private static Map<String, Object> sortJsonObject(String jsonString) throws Exception {
        Map<String, Object> jsonMap = objectMapper.readValue(jsonString, HashMap.class);
        Map<String, Object> sortedMap = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
        sortedMap.putAll(jsonMap);
        return sortedMap;
    }

    // 字符串加密方法
    private static String encryptString(String secretKey,String valueToEnc) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        byte[] encryptedValue = cipher.doFinal(valueToEnc.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedValue);
    }

    // 字符串解密方法
    private static String decryptString(String secretKey , String encryptedValue) throws Exception {
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), "AES");
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        byte[] original = Base64.getDecoder().decode(encryptedValue);
        byte[] decryptedValue = cipher.doFinal(original);
        return new String(decryptedValue, StandardCharsets.UTF_8);
    }

    public static void main(String[] args) throws Exception {
        List<String> l = new ArrayList<>();
        l.add("d");
        l.add("1");
        l.add("d23");

//        UserAuthEditDto dto = new UserAuthEditDto();
//        dto.setIp("127.3.2.1");
//        dto.setAuthCode(l);
//        dto.setUserId("sdf23er");
//        dto.setAuthUserId("xcfdghgh");

        /**
         * {
         *     "authUserName": "何牧",
         *     "authCode": "ONLY_READ",
         *     "phone": "15622230003",
         *     "ip": "124.234.182.57",
         *     "sign": "q4m3HPIzMAid1lyvPKa4JfD/dg6NkYldGA8IxL8m4Zqn8AgHji5q05rN9yuW0wIKhIjFAhhyO0uod3b14fM5vrXWdUCLEFthoKetJk8/+R7ZAutGakNxiQh0g1hHWMzBVk6tEY8NRG3udfvx9z3cF3fmTTvoBLotrT8cKMl6E7F3mokZYcqxZ3AH4pbHFZIv",
         *     "userName": "刘香君",
         *     "authPhone": "15112411771"
         * }
         */

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("phone", "15622230003");
//        jsonObject.put("userName", "刘香君");
//        jsonObject.put("authPhone", "15112411771");
//        jsonObject.put("authUserName", "何牧");
//        jsonObject.put("ip", "124.234.182.57");
//        jsonObject.put("authCode", "ONLY_READ");
//
//        String salt = "fme0o32jtkHiALdI";
//        String sign = JsonDataSecurity.encryptJsonData(jsonObject,salt);
//        jsonObject.put("sign", sign);
//        System.out.println(sign);
//        Map<String, Object>  x11  = JsonDataSecurity.decryptAndParseJsonData(sign, salt) ;
//        System.out.println(JSONUtil.toJsonStr(x11));


        JSONObject jsonObject1 = new JSONObject();
        jsonObject1.put("password", "nmgYjt@123456");
        jsonObject1.put("username", "13800000198");

        String encryptStr = JsonDataSecurity.encryptJsonData(jsonObject1, "O64WVKRobZNX5kKs70HUNVKgnXRdpiUU");
        System.out.println("对JSON对象按照键名排序并加密dtoStr:"+encryptStr);
        Map<String, Object>  json1 =  JsonDataSecurity.decryptAndParseJsonData(encryptStr,"O64WVKRobZNX5kKs70HUNVKgnXRdpiUU");
        System.out.println("解密并反序列化为JSON对象"+ JSONUtil.toJsonStr(json1));

        String urlString = URLEncoder.encode(encryptStr, "utf-8");  //输出%E4%BD%A0%E5%A5%BD
        System.out.println("url编码:   "+ urlString);


        String keyWord = URLDecoder.decode(urlString, "utf-8");
        System.out.println("url解码：  "+keyWord);



        // 将普通字符创转换成application/x-www-from-urlencoded字符串
//      //输出你好
//
//        String k = "6qdyziVHuHzhgCCrD63jg94gawIZdQEdjrhYPx9+fRHD2EymxfgtpfWjfK8QmuoB7x7Awx0+t9BZyvZHMbmbvg==";
//        String urlString1 = URLEncoder.encode(k, "utf-8");
//        System.out.println(urlString1);

        /**
         * Qpg5StkNGKtAaAbNYQSda5aODJw%2FfVoN3iV7Pb2HJt%2FxmXTeC%20vBDgV8SikxljBqAI8sg%20a%2Fhmh%2FiaIGOpldwQ%3D%3D
         * Qpg5StkNGKtAaAbNYQSda5aODJw%2FfVoN3iV7Pb2HJt%2FxmXTeC%2BvBDgV8SikxljBqAI8sg%2Ba%2Fhmh%2FiaIGOpldwQ%3D%3D
         *
         * http://58.18.173.228:90/#/login?ciphertext=Qpg5StkNGKtAaAbNYQSda5aODJw%2FfVoN3iV7Pb2HJt%2FxmXTeC%20vBDgV8SikxljBqAI8sg%20a%2Fhmh%2FiaIGOpldwQ%3D%3D
         * &businessId=ai-8cea0ec2550244f5bdf4bb4c86734710
         *  nestingLogin:{"ciphertext":"Qpg5StkNGKtAaAbNYQSda5aODJw/fVoN3iV7Pb2HJt/xmXTeC vBDgV8SikxljBqAI8sg a/hmh/iaIGOpldwQ==",
         *  "businessId":"ai-8cea0ec2550244f5bdf4bb4c86734710"}
         *  salt:O64WVKRobZNX5kKs70HUNVKgnXRdpiUU
         */
    }


}
